<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<script>
    /**
     * @param {number} n
     * @return {number[][]}
     */
    /**
     * @param {number} n
     * @return {number[][]}
     */
    var generateMatrix = function(n) {
        var result = new Array(n);
        for (let z = 0; z < n; z++) {
            result[z] = new Array(n).fill(0);
        }
        let i = j = 0;
        let index = 1;
        while (true) {
            while (true) {
                result[j][i] = index++;
                if (index > n * n) {
                    return result;
                }
                i++;
                if (i == n - 1) {
                    break;
                }
                if (result[j][i + 1] != 0) {
                    break;
                }
            }
            while (true) {
                result[j][i] = index++;
                if (index > n * n) {
                    return result;
                }
                j++;
                if (j == n - 1) {
                    break;
                }
                if (result[j + 1][i] != 0) {
                    break;
                }
            }
            while (true) {
                result[j][i] = index++;
                if (index > n * n) {
                    return result;
                }
                i--;
                if (i == 0) {
                    break;
                }
                if (result[j][i - 1] != 0) {
                    break;
                }
            }
            while (true) {
                result[j][i] = index++;
                if (index > n * n) {
                    return result;
                }
                j--;
                if (j == 1) {
                    break;
                }
                if (result[j - 1][i] != 0) {
                    break;
                }
            }
        }
    };

    console.log(generateMatrix(4));
</script>

<body>

</body>

</html>